package com.demo.webapp.validator.adapter;

import com.opensymphony.xwork2.validator.FieldValidator;
import com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator;
import com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator;

/**
 * 必填项转换
 * {validate:{rangelength:[5, 10], messages:{rangelength:'Please enter min - max string'}}}
 * 		<pre>
 *&lt;field-validator type="stringlength"&gt;
 *  &lt;param name="minLength"&gt;5&lt;/param&gt;
 *  &lt;param name="maxLength"&gt;20&lt;/param&gt;
 *  &lt;message>Please enter ${min} - ${max} string&lt;/message&gt; 
 *&lt;/field-validator&gt;
 *	</pre>
 * @author ryuu.kk
 *
 */
public class StringLengthValidateAdapter implements ValidateAdapter {

	/**
	 * 后端服务器类型
	 */
	private static final String VALIDATION_SERVER = "stringlength";
	
	/**
	 * 前置Metadata字符串
	 */
	private static final String VALIDATION_CLIENT = "rangelength";
	
	public StringLengthValidateAdapter(){}
	
	@Override
	public TransWrapper convert(FieldValidator fV) {

		TransWrapper wrapper = new TransWrapper();
		StringLengthFieldValidator sfV = (StringLengthFieldValidator) fV;
		Integer max = sfV.getMaxLength();
		Integer min = sfV.getMinLength();
		
		wrapper.setKey(VALIDATION_CLIENT);
		wrapper.setType(VALIDATION_SERVER);
		wrapper.setMessage(fV.getMessage(fV.getFieldName()));
		
		//Map<String, Object> validateExtendMap = new HashMap<String, Object>();
		if (min < 0) {
			min = 0;
		}
		if (max < 0) {
			max = 0;
		}
		wrapper.setValidation("[" + min + ", " + max + "]");
		//validateExtendMap.put("min", min);
		//validateExtendMap.put("max", max);
		//wrapper.setExtendMap(validateExtendMap);
		
		//wrapper.setValidation("true");
		//wrapper
		return wrapper;
	}

	@Override
	public boolean support(FieldValidator fV) {
		return (fV != null && fV.getValidatorType().equalsIgnoreCase(VALIDATION_SERVER));
	}

}
